#include <sys/types.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

/***
 * 自编多进程，还是不确定waitpid的用法，最后暂用wait替代
 **/

static void pr_exit(pid_t pid, int status)
{
    if(WIFEXITED(status))
    {
        printf("normal termination , exit pid= %d, status = %d\n",
            pid,WIFEXITED(status));
    }
    else if(WIFSIGNALED(status))
    {
        printf("abnormal termination, pid= %d, signal nmber= %d%s\n", 
            pid,WTERMSIG(status),
#ifdef WCOREDUMP
            WCOREDUMP(status) ? "(core file.generated)" : "");
#else
            "");
#endif
    }
    else if(WIFSTOPPED(status))
    {
        printf("child stopped, pid= %d, signal number %d\n",
            pid,WSTOPSIG(status));
    }
}

typedef struct {
    pid_t pid;
    int status;
} cc_t;

typedef struct {
    int length;
    cc_t *ptr;
} rt_t;

static rt_t *global;

static void thread()
{   
    //cc_t *cc = (*pcc);
    int time=0;
    char buf[512]="\0";
    pid_t pid = getpid();
    while(time<5)
    {    
        sprintf(buf,"pid ->%d, %d running...\n",pid, time+1);
        write(STDOUT_FILENO,buf, sizeof(buf)-1);
        sleep(5);
        time++;
    }
    char buf2[512]="\0";
    sprintf(buf2,"pid ->%d, exit\n",pid);
    write(STDOUT_FILENO,buf2, sizeof(buf2)-1);
    _exit(0);
}

void printThreads(){
    int i;
    for(i=0;i<global->length;i++)
    {
        cc_t* cc = & global->ptr[i];
        printf("main p-> %p - pid->%d - status->%d\n", cc ,cc->pid,cc->status);
    }
}


int main(void){
    rt_t g_rt;
    g_rt.length=4;
    g_rt.ptr = malloc(sizeof(cc_t) * 4);
    global = &g_rt;
    int i;
    cc_t *cc;
    for(i=0;i<global->length;i++)
    {   
        //cc_t *inner_cc = *cc;
        cc = &global->ptr[i];
        pid_t genPid = fork();
        //cc->pid = fork();
        if(genPid<0)
        {
            printf("%d thread create fail\n",i);
        }
        else if(genPid == 0)
        {
            thread();
        }
        else{
            printf("variable [genPid] -> %d\n",genPid);
            cc->pid=genPid;
            printf("main 's cc->address %p\n", cc);
        }
    }
    sleep(5);
    printThreads();
    sleep(10);
    int status;
    for(int i=0;i<global->length;i++){
        pid_t childPid = wait(&(status));
        pr_exit(childPid, status);
    }
    exit(0);
}